/*	UseComsat class definition.
 *
*/

#include "RallyAndPatrol.h"
#include "Blackboard.h"

void RallyAndPatrol::Enter()
{
	DEBUG_PRINT("UseComsat(%p) entering.\n", this);
}

void RallyAndPatrol::Execute()
{
	std::list<BWAPI::Unit*>* bar = BB->GetBuildingsByTypeGeneral(BWAPI::UnitTypes::Terran_Barracks);
	std::list<BWAPI::Unit*>* fac = BB->GetBuildingsByTypeGeneral(BWAPI::UnitTypes::Terran_Factory);
	std::list<BWAPI::Unit*>* star = BB->GetBuildingsByTypeGeneral(BWAPI::UnitTypes::Terran_Starport);
	std::list<Base*>* bases = BB->GetBases();
	BWAPI::Position rallyTo(bases->back()->GetBaseLocation().x()*TILE_SIZE,bases->back()->GetBaseLocation().y()*TILE_SIZE);
	if(fac)
	{
		for(std::list<BWAPI::Unit*>::iterator it = fac->begin(); it != fac->end(); it++)
		{
			if((*it)->getRallyPosition() == BWAPI::Position(0,0))
				(*it)->setRallyPoint(BWAPI::Position(rallyTo.x()+rand()%101 - 200,rallyTo.y()+rand()%101 - 200));
		}
	}
	if(star)
	{
		for(std::list<BWAPI::Unit*>::iterator it = star->begin(); it != star->end(); it++)
		{
			if((*it)->getRallyPosition() == BWAPI::Position(0,0))
				(*it)->setRallyPoint(BWAPI::Position(rallyTo.x()+rand()%101 - 200,rallyTo.y()+rand()%101 - 200));
		}
	}
	if(bar)
	{
		for(std::list<BWAPI::Unit*>::iterator it = bar->begin(); it != bar->end(); it++)
		{
			if((*it)->getRallyPosition() == BWAPI::Position(0,0))
				(*it)->setRallyPoint(BWAPI::Position(rallyTo.x()+rand()%101 - 200,rallyTo.y()+rand()%101 - 200));
		}
	}
	
	control->FinishWithSuccess();
}

void RallyAndPatrol::Exit()
{
	lastUsed = BWAPI::Broodwar->getFrameCount();
	DEBUG_PRINT("Exiting RallyAndPatrol behavior.\n");
}

bool RallyAndPatrol::CheckConditions()
{
	DEBUG_PRINT("Checking RallyAndPatrol conditions.\n");
	std::list<BWAPI::Unit*>* bar = BB->GetBuildingsByTypeGeneral(BWAPI::UnitTypes::Terran_Barracks);
	std::list<BWAPI::Unit*>* fac = BB->GetBuildingsByTypeGeneral(BWAPI::UnitTypes::Terran_Factory);
	std::list<BWAPI::Unit*>* star = BB->GetBuildingsByTypeGeneral(BWAPI::UnitTypes::Terran_Starport);
	std::list<Base*>* bases = BB->GetBases();
	if(bases)
	{
		if(bases->size() > 1)
		{
			if(bar)
			{
				for(std::list<BWAPI::Unit*>::iterator it = bar->begin(); it != bar->end(); it++)
				{
					if((*it)->isCompleted() && (*it)->getRallyPosition() == BWAPI::Position(0,0))
						return true;
				}
			}
			if (fac)
			{
				for(std::list<BWAPI::Unit*>::iterator it = fac->begin(); it != fac->end(); it++)
				{
					if((*it)->isCompleted() && (*it)->getRallyPosition() == BWAPI::Position(0,0))
						return true;
				}
			}
			if (star)
			{
				for(std::list<BWAPI::Unit*>::iterator it = star->begin(); it != star->end(); it++)
				{
					if((*it)->isCompleted() && (*it)->getRallyPosition() == BWAPI::Position(0,0))
						return true;
				}
			}
		}
	}
	return false;
}